﻿/*
 * TcpConnection.h
 *
 */
#ifndef __GDK_TCPCONNECTION_H__
#define __GDK_TCPCONNECTION_H__

#include <gdk/core/Types.h>
#include <gdk/core/Task.h>
#include <gdk/core/IO.h>
#include <gdk/core/MemoryBlock.h>
#include <gdk/net/Socket.h>


namespace gdk
{



enum TcpMss
{
	//对于时下大多数使用以太网的局域网来说，最大传输单元的值是 1,500 字节。
	//但是像 PPPoE 这样的系统会减小这个数值，通常是1492（= 1500 - 2（PPP）- 6（PPPoE））。
	DEF_TCP_MSS	= (1500-40), //576-40
};



class GDK_NET_EXPORT TcpConnection : public Socket
{
	DECLARE_CLASS_HANDLE(TcpConnection)

	friend class TcpEpoll;

public:
	enum ConnectionState
	{
		INVALID,		//无效
		CONNECTING,		//连接中
		CONNECTED,		//连接
		CONNECTTIMEOUT,	//连接超时
		CLOSED,			//连接关闭
		ABORT,			//连接中断
	};

private:
	ConnectionState	_connectionState;
	uint32_t		_connectTime;
	bool			_writeBlocking;
	bool			_readBlocking;
	int				_epoll;

protected:
	TcpConnection(void);
	__INLINE__ ~TcpConnection(void) { GDK_ASSERT(_epoll == -1); }

protected:
	__INLINE__ void setConnectionState(ConnectionState connectionState) { _connectionState = connectionState; }
public:
	__INLINE__ ConnectionState getConnectionState(void) const { return _connectionState; }

	bool   getPeerName(__sockaddr_in &sa) const;
	void   getPeerName(String &ip, uint16_t &port) const;
	String getPeerName(void) const;

public:
	virtual void    onTick(uint32_t timeSinceLastTick);
	virtual bool    attach(SOCKET s);
	virtual SOCKET  detach(void);
	virtual bool    connect(const Char *ip, unsigned short port, bool block = true);
	virtual ssize_t receive(void *buf, ssize_t len);
	virtual ssize_t send(const void *data, ssize_t len);
	virtual void    close(void);
};




}//namespace gdk


#endif /*__GDK_TCPCONNECTION_H__*/
